<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>订单详情</title>
    <link rel="stylesheet" href="/scriptZIP/indexPlus.css">
    <style scoped>
        body {
            margin: 20px;
            font-family: Arial, sans-serif;
        }

        h2,
        h3 {
            margin: 10px 0;
        }

        .el-card {
            margin-bottom: 20px;
            padding: 15px;
        }

        .el-table {
            margin-top: 10px;
        }

        .el-row {
            margin-bottom: 20px;
        }

        .el-row:last-child {
            margin-bottom: 0;
        }

        .full-width-table {
            width: 100%;
        }

        [v-cloak] {
            display: none;
        }

        .back-button {
            margin-bottom: 20px;
        }
    </style>
</head>

<body>
    <div id="orderDetailsApp" v-cloak>
        <el-container>
            <el-header>
                <h2>订单详情</h2>
            </el-header>
            <el-main>
                <!-- 返回按钮 -->
                <el-button class="back-button" @click="goBack" type="primary">返回</el-button>

                <!-- 基本信息 -->
                <el-card>
                    <h3>基本信息</h3>
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="订单类型">
                                <span>{{ order.way === 7 ? "线上" : "线下" }}</span>
                            </el-form-item>
                            <el-form-item label="订单号">
                                <span>{{ order.tradeNo }}</span>
                            </el-form-item>
                            <el-form-item label="订单建立时间">
                                <span>{{ order.time }}</span>
                            </el-form-item>
                            <el-form-item label="类型">
                                <span>{{ order.orderType === 1 
      ? "新签" 
      : order.orderType === 2 
        ? "续费" 
        : order.orderType === 3 
          ? "新签尾款" 
          : "未知类型" }}</span>
                            </el-form-item>
                            <el-form-item label="经办人">
                                <span>{{ order.handleUser }}</span>
                            </el-form-item>
                            <el-form-item label="收款日期">
                                <span>{{ order.handlingDate }}</span>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="校区名称">
                                <span>{{ order.schoolName }}</span>
                            </el-form-item>
                            <el-form-item label="学员姓名">
                                <span>{{ order.studentName }}</span>
                            </el-form-item>
                            <el-form-item label="联系电话">
                                <span>{{ order.bindCode }}</span>
                            </el-form-item>

                            <el-form-item label="业绩归属人">
                                <span>{{ order.performance }}</span>
                            </el-form-item>

                            <el-form-item label="备注信息">
                                <span>{{ order.remark || '无' }}</span>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-card>

                <!-- 课程详情 -->
                <el-card>
                    <h3>课程详情</h3>
                    <el-table :data="order.courseDetailsList" border class="full-width-table">
                        <el-table-column prop="courseName" label="课程名称" width="200"></el-table-column>
                        <el-table-column prop="quantity" label="数量" width="80"></el-table-column>
                        <el-table-column prop="coursePrice" label="总价 (元)" width="120">
                            <template #default="scope">
                                {{ (scope.row.coursePrice / 100).toFixed(2) }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="amount" label="实收 (元)" width="120">
                            <template #default="scope">
                                {{ (scope.row.amount / 100).toFixed(2) }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="msType" label="报读模式" width="100">
                            <template #default="scope">
                                <span>
                                    {{
                                    scope.row.msType === 1 ? "按课时收费" :
                                    scope.row.msType === 2 ? "按月收费" :
                                    scope.row.msType === 3 ? "按天收费" :
                                    scope.row.msType === 4 ? "按季收费" :
                                    scope.row.msType === 5 ? "按期收费" :
                                    scope.row.msType === 6 ? "按课包收费" :
                                    scope.row.msType === 7 ? "按体验收费" :
                                    "未知"
                                    }}
                                </span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="startTime" label="开课时间" width="150"></el-table-column>
                        <el-table-column prop="endTime" label="课程有效期至" width="150"></el-table-column>
                    </el-table>
                </el-card>

                <!-- 提交表单 -->
                <el-card>
                    <el-form ref="refundFormRef" :model="refundForm" :rules="rules" label-width="120px">
                    <h3>退课详情</h3>
                    <el-table :data="refundForm.courses" border style="width: 100%">
                        <el-table-column prop="courseName" label="课程名称" width="200">
                            <template #default="scope">
                                <el-select v-model="scope.row.courseId" placeholder="请选择课程" style="width: 100%">
                                    <el-option v-for="course in order.courseDetailsList" :key="course.courseId"
                                        :label="course.courseName" :value="course.courseId">
                                    </el-option>
                                </el-select>
                            </template>
                        </el-table-column>
                        <el-table-column prop="usedDays" label="已课销天数" width="150">
                            <template #default="scope">
                                <el-input-number v-model="scope.row.usedDays" :min="0" style="width: 100%"
                                    placeholder="已课销天数"></el-input-number>
                            </template>
                        </el-table-column>
                        <el-table-column prop="usedAmount" label="已课销金额 (元)" width="150">
                            <template #default="scope">
                                <el-input-number v-model="scope.row.usedAmount" :min="0" :precision="2" :step="0.01"
                                    style="width: 100%" placeholder="已课销金额"></el-input-number>
                            </template>
                        </el-table-column>
                        <el-table-column prop="balance" label="余额 (元)" width="150">
                            <template #default="scope">
                                <el-input-number v-model="scope.row.balance" :min="0" :precision="2" :step="0.01"
                                    style="width: 100%" placeholder="余额"></el-input-number>
                            </template>
                        </el-table-column>
                        <el-table-column prop="refundAmount" label="实际退款金额 (元)" width="150">
                            <template #default="scope">
                                <el-input-number v-model="scope.row.refundAmount" :min="0" :precision="2" :step="0.01"
                                    style="width: 100%" placeholder="退款金额"></el-input-number>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" width="100">
                            <template #default="scope">
                                <el-button type="text" size="small" @click="removeCourse(scope.$index)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <el-button type="primary" @click="addCourse" size="small" style="margin: 10px 0">新增课程</el-button>

                    <!-- 收款信息 -->
                    <h3>收款信息</h3>
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="收款方式" prop="paymentType">
                                <el-radio-group v-model="refundForm.paymentType">
                                    <el-radio label="转账">转账</el-radio>
                                    <el-radio label="现金">现金</el-radio>
                                </el-radio-group>
                            </el-form-item>
                            <el-form-item v-if="refundForm.paymentType === '转账'" label="收款银行及支行" prop="bankBranch">
                                <el-input v-model="refundForm.bankBranch" placeholder="请输入银行及支行"></el-input>
                            </el-form-item>
                            <el-form-item v-if="refundForm.paymentType === '转账'" label="收款账号" prop="bankAccount">
                                <el-input v-model="refundForm.bankAccount" placeholder="请输入收款账号"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="收款人" prop="receiver">
                                <el-input v-model="refundForm.receiver" placeholder="请输入收款人"></el-input>
                            </el-form-item>

                            <el-form-item label="申请日期" prop="applyDate">
                                <el-date-picker v-model="refundForm.applyDate" type="date" placeholder="请选择日期"
                                    format="YYYY-MM-DD" value-format="YYYY-MM-DD">
                                </el-date-picker>
                            </el-form-item>
                            <el-form-item label="备注" prop="remark">
                                <el-input v-model="refundForm.remark" placeholder="请输入备注"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <!-- 提交按钮 -->
                    <el-form-item>
                        <el-button type="primary" @click="submitForm">提交</el-button>
                        <el-button @click="resetForm">重置</el-button>
                    </el-form-item>
                </el-card>
            </el-form>
            </el-main>
        </el-container>
    </div>

    <script src="/scriptZIP/vue.global.js"></script>
    <script src="/scriptZIP/index.full.js"></script>
    <script src="/scriptZIP/axios.min.js"></script>
    <script src="/scriptZIP/zh-cn-plus.js"></script>
    <script>
        const { createApp } = Vue;

        createApp({
            data() {
                return {
                    order: {},
                    refundForm: {
                        courses: [ // 初始为空，可动态新增
                            {
                                courseId: '',
                                courseName: '',
                                usedDays: 0,
                                usedAmount: 0,
                                balance: 0,
                                refundAmount: 0
                            }
                        ],
                        paymentType: '转账', // 默认值
                        bankBranch: '',
                        bankAccount: '',
                        receiver: '',
                        applyDate: '',
                        remark: ''
                    },
                    rules: {
                        paymentType: [{ required: true, message: '请选择收款方式', trigger: 'change' }],
                        applyDate: [{ required: true, message: '请选择申请日期', trigger: 'change' }],
                        remark: [{ required: true, message: '请填写备注', trigger: 'blur' }] // ✅ 新增备注必填
                    }
                };
            },
            created() {
                const id = this.getParams().id;
                axios.get(`/pc/order/orderDetails/${id}`).then(response => {
                    this.order = response.data;
                    this.refundForm.courses = response.data.courseDetailsList.map(course => ({
                        id: course.id,
                        courseId: course.courseId,
                        courseName: course.courseName,
                        usedDays: 0,
                        usedAmount: 0,
                        balance: 0,
                        refundAmount: 0
                    }));
                }).catch(error => {
                    console.error("Error fetching order details:", error);
                });
            },
            methods: {
                addCourse() {
                    this.refundForm.courses.push({
                        courseId: '',
                        courseName: '',
                        usedDays: 0,
                        usedAmount: 0,
                        balance: 0,
                        refundAmount: 0
                    });
                },
                // 删除课程
                removeCourse(index) {
                    this.refundForm.courses.splice(index, 1);
                },
                getParams() {
                    const query = location.search.substring(1);
                    const vars = query.split("&");
                    const params = {};
                    for (let i = 0; i < vars.length; i++) {
                        const pair = vars[i].split("=");
                        params[pair[0]] = decodeURIComponent(pair[1]);
                    }
                    return params;
                },
                goBack() {
                    window.history.back(); // 返回上一页
                },

                async submitForm() {
                    this.$refs.refundFormRef.validate(async (valid) => {
        if (!valid) {
            this.$message.warning('请完善必填项！');
            return;
        }

                    try {
                        for (const course of this.refundForm.courses) {
                            await this.submitCourseDetail(course);
                        }
                        await this.submitRefundInfo();
                        this.$message.success('提交成功！');
                        this.resetForm();
                        window.history.back();
                    } catch (error) {
                        console.error('提交失败：', error);
                        this.$message.error('提交失败，请重试');
                    }
                });
},
            
                // 提交课程详情（逐条提交）
                async submitCourseDetail(course) {
                    const response = await axios.post('/pc/refund', {
                        orderId: this.getParams().id,
                        courseId: course.courseId,
                        courseDetailsId: course.id, // 唯一 ID
                        withdrawnDays: course.usedDays,
                        withdrawnAmount: course.usedAmount * 100,
                        balance: course.balance * 100,
                        refundAmount: course.refundAmount * 100
                    });
                    return response.data;
                },

                // 提交退款基础信息
                async submitRefundInfo() {
                    const response = await axios.post('/pc/order/refundApply', {
                        id: this.getParams().id,
                        paymentMethod: this.refundForm.paymentType === '转账' ? 1 : 2, // 1: 转账，2: 现金
                        recipient: this.refundForm.receiver,
                        bankBranch: this.refundForm.bankBranch,
                        accountNumber: this.refundForm.bankAccount,
                        applicationDate: this.refundForm.applyDate,
                        notes: this.refundForm.remark,
                        refundApplicant: localStorage.getItem('staffUserId'),
                        refundApprovalStatus: 0, // 默认状态为 0
                        refund: this.refundForm.courses.reduce((total, course) => total + course.refundAmount, 0) * 100 // 计算课程总金额
                    });
                    return response.data;
                },
                // 重置表单
                resetForm() {
                    this.refundForm = {
                        courses: [
                            {
                                courseName: '',
                                usedDays: 0,
                                usedAmount: 0,
                                balance: 0,
                                refundAmount: 0
                            }
                        ],
                        paymentType: '转账',
                        bankBranch: '',
                        bankAccount: '',
                        receiver: '',
                        applyDate: '',
                        remark: ''
                    };
                }
            }
        }).use(ElementPlus, { locale: ElementPlusLocaleZhCn }).mount("#orderDetailsApp");
    </script>
</body>

</html>